package br.ucb.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import br.ucb.connection.FactoryConnection;
import br.ucb.entity.Disciplina;

public class DisciplinaDAO {

	/* Insere Disciplina */
	public static void insertDisciplina(Disciplina disciplina)
			throws SQLException, ClassNotFoundException {
		Connection con = FactoryConnection.getInstance().criaConexao();
		PreparedStatement ps = null;
		String SQL_INSERT = "INSERT INTO Disciplina(nomeDisciplina,objetivo,cargaHoraria,nivelMedio)"
				+ "values(?,?,?,?);";

		ps = con.prepareStatement(SQL_INSERT);
		ps.setString(1, disciplina.getNomeDisciplina());
		ps.setString(2, disciplina.getObjetivo());
		ps.setInt(3, disciplina.getCargaHoraria());
		ps.setDouble(4, disciplina.getNivelMedio());

		ps.executeUpdate();

		con.close();
		ps.close();
	}

	/*
	 * idDisciplina int(6) NOT NULL AUTO_INCREMENT, 
	 * nomeDisciplina varchar(50)NOT NULL, objetivo varchar(500) NOT NULL, cargaHoraria int(5)
	 * NOT NULL, nivelMedio int(2) NOT NULL, PRIMARY KEY (idDisciplina)
	 */
	/* Procura id da ultima disciplina inserida no banco*/
	public static Integer getLastId() throws SQLException, ClassNotFoundException {
		Integer id = 0;
		Connection con = FactoryConnection.getInstance().criaConexao();
		String SQL_SELECT = "SELECT last_insert_id(idDisciplina) from Disciplina;";
		PreparedStatement ps = null;
		ResultSet rs = null;
		ps = con.prepareStatement(SQL_SELECT);
		// ps.setInt(1,id_bolao);
		rs = ps.executeQuery();
		while (rs.next()) {
			id = rs.getInt(1);
		}
		ps.close();
		con.close();
		return id;
	}
	/* Procura Disciplina pegando o ultimo id que foi inserido no banco */
	public static Disciplina getDisciplinaByLastId() throws SQLException,ClassNotFoundException {
		Disciplina disciplina = null;
		Integer idDisciplina = DisciplinaDAO.getLastId();
		Connection con = FactoryConnection.getInstance().criaConexao();
		String SQL_SELECT = "SELECT * FROM Disciplina WHERE idDisciplina = ?;;";
		PreparedStatement ps = null;
		ResultSet rs = null;
		ps = con.prepareStatement(SQL_SELECT);
		ps.setInt(1,idDisciplina);
		rs = ps.executeQuery();
		while (rs.next()) {
			System.out.println("Aqui");
			System.out.println(rs.getInt(1));
			System.out.println(rs.getString(2));
			System.out.println(rs.getString(3));
			System.out.println(rs.getInt(4));
			System.out.println(rs.getInt(5));
			System.out.println();
			disciplina = new Disciplina(rs.getInt(1), rs.getString(2), rs.getString(3), rs.getInt(4), rs.getInt(5));
		}
		ps.close();
		con.close();
		return disciplina;
	}
}
